<?php
/**
 * Created by PhpStorm.
 * User: SATA
 * Date: 2017/9/23
 * Time: 15:30
 */

namespace app\home\model;
use think\Model;

class Appointment extends Model
{
    protected $autoWriteTimestamp = "datetime";

    /**
     * 获取订单详情
     * @param milit $id 订单id
     * @param boolean $field 订单查询字段
     * @return array 订单详情
     */
    public function info($id,$field=true){
        $map = array();
        if($id){
            $map['uid']=uid;
        }
        else
            return $this->error("错误的id参数");
        return $this->field($field)->where($map)->find();
    }

    /**
     * 获取订单列表
     * @param milit $id 学生id
     * @param int $status 状态
     * @param string $order 排序规则
     * @return array 订单列表数组
     */
    public function lists($id,$order='`uid` DESC'){
        $map = array();
        if($id){
            $map['student_id']=$id;
        }
        else
            return $this->error('错误的id参数');
        if(input('status'))
            $map['status'] = input('status');
        else
            unset($map['status']);
        $teacher = Model('document')->where(['status'=>1])->field('id,name,title,second_title,description,cover_id,icon')->buildSql();
        /*与文档联合查询*/
        $info = $this->alias('a')->join([$teacher=> 'w'], 'a.teacher_id = w.id')->where($map)->order($order)->select();
        return $info;
    }

    /**
     * 创建新的订单
     * @param int $sid 学生id
     * @param int $tid 教师id
     * @param datatime $apt_time 预约时间
     * @param int $status 订单状态1-正常
     * @return int 订单id
     */
    public function create_order($sid,$tid,$apt_time,$status=1){
        $data = array();
        $data['student_id'] = $sid;
        $data['teacher_id'] = $tid;
        $data['appoint_time'] = $apt_time;
        $data['status'] = $status;
        $result = $this->validate(true)->save($data);
        if(false===$result)
            return $this->getError();
        return $result;
    }

    /**
     * 用户订单详细
     * @param int $sid 学生id
     * @param int $uid 订单id
     * @return array 详情
     */
    public function order_detail($sid,$uid){
        $map['student_id']=$sid;
        $map['uid']=$uid;
        $result = $this->where($map)->find()->toArray();
        if(false == $result)
            return $this->getError();
        $teacher = Model('Document')->detail($result['teacher_id']);
        if(false == $teacher)
            return $teacher->getErroe();
        $result = array_merge($teacher,$result);
        return $result;
    }

    /**
     * 取消预约
     * @param int $uid  订单id
     * @return
    */
    public function order_cancel($sid,$uid){
        $map = array();
        $map['student_id'] = $sid;
        $map['uid'] = $uid;
        $order = $this->where($map)->find();
        if(strtotime(date("y-m-g h:i:s"))+config("critical_time")*60<strtotime($order['appoint_time'])){
            $data = array("status"=>-1);
            $this->save($data,$map);
            return true;
        }
    }
}